<template>
  <div class="home">
    <div>
      <PageLoading v-if='isShowLoading'/>
      <!-- <PageLoading /> -->

      <OpenOnBrowser v-if="isShowOpenOnBrowser" @hide="toggleMask"/>

      <div class="swiper-container swiper-container-horizontal">
        <div class="swiper-wrapper">
          <div class="swiper-slide swiper-no-swiping" :key="img.imageKey" v-for="img in imageKeyTimeArray">
            <div class="horizontal-img"><img :src="img.imgUrl"></div>
          </div>
        </div>

        <div class="subtilte-wrap-1 swiper-no-swiping">
          <div class="subtilte-1" v-if="curSentenceText">
            {{curSentenceText}}
          </div>
        </div>
      </div>

      <audio :src="audioUrl" id="audioPlayer" controls="controls" style="width: 0; height: 0; visibility: hidden;"/>

      <div v-if="longCurSentenceText" style="text-align: center">
        <span>
        <pre class="long_sentence">{{ longCurSentenceText }}</pre>
        </span>
      </div>

      <div class="container">
        <!-- 书籍信息 -->
        <div class=" book-info-container">
          <div class="book-info-wrapper">
            <div class="title">{{ bookName }}</div>
            <div class="share-wrapper" @click="share">
              <span class="icon"></span>
              分享
            </div>
          </div>
        </div>

        <!-- 用户信息 -->
        <div class=" user-info-container">
          <!-- 头像 -->
          <div class="img-wrapper">
            <router-link :to="audioListStr">
              <img class="avatar" :src="avatar">
            </router-link>
          </div>

          <!-- 其他信息 -->
          <div class="user-info-wrapper">
            <div class="nickname">
              <router-link :to="audioListStr">
                {{ nickname }}
              </router-link>
            </div>
            <div class="user-age">年龄：{{ age }}</div>

            <div class="upload-container">
              <span class="upload-time">上传：{{ recordingDate }}</span>
            </div>
          </div>

          <div class="score-info-wrapper" v-if="score">
            <div class="score">
              <span class="num">{{ score }}</span>
              <span>分</span>
            </div>
            <div class="desc">综合得分</div>
          </div>
        </div>

        <!-- 评分详情 -->
        <div class=" score-detail-container" v-if="score">
          <div class="score-detail-wrapper">
            <div>
              <p class="score"><span class="num">{{ accuracy }}</span>分</p>
              发音
            </div>
            <div>
              <p class="score"><span class="num">{{ completion }}</span>分</p>
              完成度
            </div>
            <div>
              <p class="score"><span class="num">{{ fluency }}</span>分</p>
              流利度
            </div>
          </div>
        </div>

        <!-- 点赞数 -->
        <div class=" praise-container">
          <div :class="[{ active: isViewerLike }, 'praise-icon-container']" @click="submitPraise()">
            <span class="icon"/>
          </div>
          <p class="desc">
            <span class="num">{{ likes }}</span> 人点赞
          </p>
          <div class="history-container">
            <div class="history">
              <router-link :to="audioListStr">
                <span class="icon"></span>
                其他分享
              </router-link>
            </div>

            <span class="download"><a :href="audioUrl" @click="download()">下载 mp3</a></span>
          </div>
        </div>
      </div>

      <div class="mt">
        <!-- 评论 -->
        <div class="comment-container">
          <div class="container">
            <div class="header"
                 ref="comment-header">
              <span class="title">
                <span>
                  作品评论
                </span>
              </span>

              <span class="login-status" @click="login" v-if="!userInfo.token">
                {{ orgName }}登录
              </span>
            </div>
          </div>

          <div class="container">
            <div class="input-container">
              <input type="text" placeholder="我来说两句" v-model="commentTxt">

              <button class="comment-btn" @click="submitComment">评论
              </button>
            </div>
          </div>

          <div class="container">
            <div class="comment-list" v-if="comments.length > 0">
              <Comment v-for="(item, index) in comments"
                       :key="index"
                       :commentData="item"
                       :userInfo="userInfo"
                       @deleteComment="deleteComment">
              </Comment>

              <div class="comment-loading-tips">
                <span v-if="isCommentsMore && isCommentLoading">加载中...</span>
                <span v-if="!isCommentsMore">没有更多数据咯~</span>
              </div>
              <!-- <button class="more"
                      v-if="isCommentsMore"
                      @click="moreComment">
                <span v-if="!isCommentLoading">
                  查看更多评论<span class="icon"></span>
                </span>
                <span v-else>加载中...</span>
              </button> -->
            </div>
            <div v-else-if="!viewerid" class="login-need">
              需要登录才能看到用户评论哦~
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  // @ is an alias to /src
  // import HelloWorld from '@/components/HelloWorld.vue'
  import BScroll from '@better-scroll/core'
  import MouseWheel from '@better-scroll/mouse-wheel'
  import cookie from 'js-cookie'
  import $ from 'jquery'
  import qs from 'qs'
  import _get from 'lodash/get'
  import Swiper from 'swiper'
  import {OSS_IMAGE_URL_PREFIX, OSS_RECORDING_URL_PREFIX} from '../constances/constances'
  import '../audioplayer.js'
  import {getAge, getCurrentDateStr, isWx} from '../utils/util';
  import PageLoading from '@/components/PageLoading'
  import OpenOnBrowser from '@/components/OpenOnBrowser'
  import Comment from '@/components/Comment'

  import 'swiper/dist/css/swiper.min.css'

  const PAGE_SIZE = 10

  // 注册插件
  BScroll.use(MouseWheel)

  export default {
    name: 'home',
    components: {
      PageLoading,
      OpenOnBrowser,
      Comment
    },
    data() {
      return {
        orgId: undefined, // 机构id
        orgName: '', // 机构名字
        viewerid: undefined, // 用户id
        isShowOpenOnBrowser: false,
        isShowLoading: true,
        tryTimes: 0,
        nickname: '', // 分享者昵称
        audioShareRecordingData: {}, // 分享数据
        audioUrl: '', // 音频地址
        avatar: '', // 分享者头像
        audioListStr: '', // 分享列表
        birthday: '',
        age: '', // 用户使用时间
        bookName: '', // 书名
        episode: '', // 简介
        score: '', // 语音分数
        accuracy: '', // 准确度
        completion: '', // 完成度
        fluency: '', // 流利度
        recordingDate: '', // 上传时间
        recordingAge: '', // 上传年龄
        imageKeyTimeArray: [], // swiper
        sentenceTimeArray: [], // 字幕数据
        recordingType: '',
        curSentenceText: '', // 当前字幕
        longCurSentenceText: '', // 当前字幕
        isViewerLike: false, // 当前用户是否点赞
        likes: 0, // 录音点赞数
        comments: [], // 评论列表
        userInfo: {},
        commentTxt: '',
        isCommentLoading: false, // 评论加载中
        isCommentsMore: false, // 是否有下一页，
      }
    },
    beforeRouteEnter(to, from, next) {
      // 在渲染该组件的对应路由被 confirm 前调用
      // 不！能！获取组件实例 `this`
      // 因为当守卫执行前，组件实例还没被创建
      const {code} = qs.parse(location.search.replace('?', ''))
      const {orgid} = to.query
      const userCachJson = cookie.get('user')
      const userCach = userCachJson && JSON.parse(userCachJson)
      const openid = _get(userCach, 'openid');
      if (isWx() && !code && !openid) {
        // 如果是微信浏览器， 强制去登录
        const redirect_uri = encodeURIComponent(location.href)
        if (!orgid || orgid == 0) {
          const appid = 'wx22cfbbf1acbf0274'
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        } else if (orgid == 101) {
          console.log('巧读')
          const appid = 'wx0c9aa07cc183ba0b'
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        }
      }
      next()
    },
    methods: {
      // 获取机构名字
      getOrgName() {
        const orgid = this.$route.query.orgid
        this.orgId = orgid

        console.log('orgid', orgid)
        if (orgid !== undefined) {
          this.$api.organization.getOrgName({
            orgid
          }).then(data => {
            if (data) {
              this.orgName = data
              this.init()
            }
          })
        }
      },

      // 点击登录
      login() {
        // const redirect_uri = encodeURIComponent(location.href)
        // // const redirect_uri = 'https%3A%2F%2Fwww.read1000.com%2FAudioShare%2FAudioShare.html%3Fuid%3D1204%26recid%3D1550046996019000%26orgid%3D0I'

        // if (this.$parent.isWx) {
        //   window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx22cfbbf1acbf0274&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
        // } else {
        //   this.$message({
        //     message: '请用微信浏览器打开本页面，然后进行登录！',
        //     duration: 1500,
        //   })
        // }
        this.$read1000Login({
          org_id: this.$route.query.orgid,
          successCb: (data) => {
            this.userInfo = {
              ...this.userInfo,
              nickname: data.user.nickname,
              user_id: data.user.user_id,
              headimgurl: OSS_RECORDING_URL_PREFIX + data.user.avatar_url,
              token: data.token
            }
            this.viewerid = data.user.user_id
            cookie.set('user', this.userInfo, {expires: 0.08})
            this.getCommentListData().then(() => {
              this.$nextTick(() => {
                this.initScroll()
              })
            })
            this.$message({
              message: '登录成功！',
              duration: 1500,
            })
          }
        })
      },
      // 获取用户数据
      getUserInfo() {
        console.log(123123)
        return new Promise((resolve, reject) => {
          const userCachJson = cookie.get('user')
          if (userCachJson) {
            this.userInfo = JSON.parse(userCachJson)
            this.viewerid = this.userInfo.user_id || this.userInfo.openid || ''
            resolve()
          } else {
            if (this.$parent.isWx) {
              // 微信端获取用户数据
              const {code} = qs.parse(location.search.replace('?', ''))
              const {orgid} = this.$route.query
              if (code) {
                // 获取code 成功
                this.$api.user.getUserInfoData({
                  code,
                  orgid
                }).then(data => {
                  if (data.openid) {
                    // 判断获取到用户数据
                    this.userInfo = data
                    this.viewerid = data.openid
                    cookie.set('user', data, {expires: 0.08})
                  }
                  resolve()
                }).catch(err => {
                  reject(err)
                })
              } else {
                // 没有带code 游客身份
                resolve()
              }
            } else {
              // todo
              // this.viewerid = undefined
              resolve()
            }
          }
        })
      },

      // 异步获取录音数据
      getAudioShareData() {
        const {uid, recid} = this.$route.query
        return this.$api.shareRecord.getShareRecord({
          uid,
          recid
        }).then(data => {
          this.initRecordingData(data)
          // 分享标题有书名 所以要获取到数据才可以分享
          this.initWx();
        }).catch(() => {
          this.tryTimes++
          if (this.tryTimes < 3) {
            this.getAudioShareData() //再试一次
          } else {
            console.log(123)
          }
        })
      },

      // 异步获取评论数据
      getCommentListData(start = 0, end = PAGE_SIZE - 1, isRefresh = false) {
        const {recid} = this.$route.query
        const {viewerid} = this
        this.isCommentLoading = true
        return this.$api.comment.getCommentList({
          recid,
          viewerid,
          start,
          end
        }).then(data => {
          console.log('啊啊啊啊1', new Date().getTime())
          this.isCommentLoading = false
          // this.initRecordingData(data)
          const {likes, isViewerLike, recordingComment, recording_id} = data;
          if (recording_id) {
            // 判断请求到数据
            this.likes = likes
            this.isViewerLike = isViewerLike
            // this.comments = recordingComment.comments || []
            if (isRefresh) {
              this.comments = recordingComment.comments
            } else {
              this.comments = [
                ...this.comments,
                ...recordingComment.comments,
              ]
            }

            if (recordingComment.comments.length === PAGE_SIZE) {
              this.isCommentsMore = true
            } else {
              this.isCommentsMore = false
            }
          }
        }).catch(() => {
          this.isCommentLoading = false
        })
      },


      // 获取更多评论
      moreComment() {
        if (this.isCommentLoading) {
          return
        }

        if (this.isCommentsMore) {
          this.getCommentListData(this.comments.length, (this.comments.length + PAGE_SIZE - 1))
        }
      },


      // 初始化数据
      initRecordingData(data) {
        this.nickname = data.nickname  //改成用昵称，用户可以改昵称
        this.audioShareRecordingData = data.recordingList[0]
        const {
          osskey, user_id, book, episode, voice_score,
          pron_accuracy, pron_completion, pron_fluency,
          date_time, json_data, recording_type
        } = this.audioShareRecordingData

        // 音频地址
        this.audioUrl = OSS_RECORDING_URL_PREFIX + osskey;

        // 用户音频列表
        this.audioListStr = `/audioList?uid=${user_id}${this.$route.query.ctype ? `&ctype=${this.$route.query.ctype}` : ''}${this.$route.query.orgid ? `&orgid=${this.$route.query.orgid}` : ''}`

        // 用户头像
        this.avatar = OSS_RECORDING_URL_PREFIX + data.avatar_url

        // 用户使用时间
        this.birthday = data.birthday
        this.age = getAge(data.birthday, getCurrentDateStr())

        // 书名
        this.bookName = book

        // 简介
        this.episode = episode

        // 得分
        if (voice_score && parseInt(voice_score, 10) > 0) {
          this.score = voice_score
          if (pron_accuracy != null) {
            // 准确度
            this.accuracy = Math.round(pron_accuracy).toString();
          }

          if (pron_completion != null) {
            // 完成度
            this.completion = Math.round(pron_completion * 100).toString();
          }

          if (pron_fluency != null) {
            // 流利度
            this.fluency = Math.round(pron_fluency * 100).toString();
          }
        }

        // 上传时间
        this.recordingDate = date_time.substring(0, 10)
        if (data.birthday != null) {
          this.recordingAge = getAge(data.birthday, this.recordingDate)
        }

        const {imageKeyTimeArray, sentenceTimeArray} = JSON.parse(json_data)
        // swiper 数据
        this.imageKeyTimeArray = imageKeyTimeArray.map(img => ({
          ...img,
          imgUrl: OSS_IMAGE_URL_PREFIX + '/' + episode + "/" + book + "/" + img.imageKey
        }))

        // 字幕数据
        this.sentenceTimeArray = sentenceTimeArray

        // subtitle
        this.recordingType = recording_type

        // 数据加载完成 更新完dom后进行 dom 操作
        this.$nextTick(() => {
          this.initAudioPlayer();
          this.initSwiper();
          this.initSingleAudio();
          this.isShowLoading = false;
        })
      },

      // 加载播放器
      initAudioPlayer() {
        $('audio').audioPlayer(
          {
            classPrefix: 'audioplayer',
            strPlay: 'Play',
            strPause: 'Pause',
            strVolume: 'Volume'
          });
      },

      // 加载swiper
      initSwiper() {
        this.mySwiper = new Swiper('.swiper-container', {
          onlyExternal: false,//值为true时，slide无法拖动，只能使用扩展API函数例如slideNext() 或slidePrev()或slideTo()等改变slides滑动
          initialSlide: 0,
          noSwiping: true
        });
      },

      // 加载音频
      initSingleAudio() {
        const media = document.getElementById("audioPlayer");

        //play 监听播放
        media.addEventListener("play", () => {

          // //可能是其它地方触发play（例如新加入的 audioPlayer），所以这里统一保证hide
          // $("#playbtns").hide();

          //=====定时器，250毫秒======
          this.timeupdate = setInterval(() => {
            //network check
            var curTime = media.currentTime;
            var duration = media.duration;
            //control slide
            //====image====
            var imageIndex = 0;
            for (; imageIndex < this.imageKeyTimeArray.length; imageIndex++) {
              var imageKeyTime = this.imageKeyTimeArray[imageIndex];
              if (curTime < Number(imageKeyTime.time)) {
                break;
              }
            }
            //当前页
            var curImageIndex = imageIndex - 1;
            if (curImageIndex < 0) curImageIndex = 0;

            if (this.mySwiper.activeIndex != Number(curImageIndex)) {
              this.mySwiper.slideTo(Number(curImageIndex));
              //subtitle
              //$("#subtitle-id").html("这是第 " +(curImageIndex+1).toString()+"页 字幕, bla bla bla");
            }

            //====sentence====
            var sentenceIndex = 0;
            for (; sentenceIndex < this.sentenceTimeArray.length; sentenceIndex++) {
              var sentenceTime = this.sentenceTimeArray[sentenceIndex];
              if (curTime < Number(sentenceTime.time)) {
                break;
              }
            }
            //当前页
            var curSentenceIndex = sentenceIndex - 1;
            if (curSentenceIndex < 0) curSentenceIndex = 0;

            var curSentenceText = this.sentenceTimeArray[curSentenceIndex].text;
            if (this.audioShareRecordingData.recording_type == 1) {
              // $("#subtitle-id-1").html(curSentenceText);
              this.curSentenceText = curSentenceText;
            } else if (this.audioShareRecordingData.recording_type == 2) {
              this.longCurSentenceText = curSentenceText;
              // var paragraphText = curSentenceText.replace(new RegExp("\n", "gm"), "<br>");
              // $("#subtitle-id-2").html(paragraphText);
            }

            //====播放完毕====
            if (curTime > duration) {
              // $("#curr_time").html(convertTime(curTime));
              // $("#duration").html(convertTime(curTime));
              $(".curr_progress").css("width", "100%");
            } else {
              // $("#curr_time").html(convertTime(curTime));
              // $("#duration").html(convertTime(duration));
              $(".curr_progress").css("width", curTime / duration * 100 + "%");
            }

            //====一旦开始播放，就隐藏 loading 按钮====
            if (curTime > 0) {
              $("#loading").hide();//这里 hiding #loading
            }

          }, 250);

          //pause
          media.addEventListener("pause", function () {
            clearInterval(this.timeupdate);//停止定时器
          });

          //end
          media.addEventListener("ended", () => {
            this.audioFinish();
          });

          //error
          media.addEventListener("error", function () {
            //alert("音频加载期间发生错误！");
            console.warn("音频加载期间发生错误！");
            //hidePlayBtn();
          });

          //emptied
          media.addEventListener("emptied", function () {
            //alert("对不起，目前的播放列表为空，不能播放！");
            console.warn("对不起，目前的播放列表为空，不能播放！");
            //hidePlayBtn();
          });

        });
      },

      // 加载微信
      initWx() {

        const {orgid, ctype} = this.$route.query

        if (this.$parent.isWx) {
          let shareTitle = `${this.orgName}：阅读的力量`;
          if (ctype == 6 || orgid == 101)
            shareTitle = "巧读";
          const shareImageUrl = "https://read1000.com/AudioShare/images/thumb.png";
          const shareDescContent = "我分享了 " + this.nickname + " 的朗读：\n《" + this.bookName + "》"
          const shareLink = window.location.href

          if (!orgid || orgid == 0 || orgid == 101 || orgid == 201) {
            this.$api.shareRecord.getWxConfig({
              url: window.location.href.split('#')[0]
            }).then(data => {
              this.$wechat.inWxJsApi(
                false,
                data.appId,
                data.timestamp,
                data.nonceStr,
                data.signature,
                shareImageUrl,
                shareLink,
                shareDescContent,
                shareTitle,
              )
            })
          }
        }
      },

      audioFinish() {
        clearInterval(this.timeupdate);// 停止定时器
        this.curSentenceText = '' // 清空字幕
        this.longCurSentenceText = '' // 清空字幕
        if (this.mySwiper.activeIndex != 0) {
          this.mySwiper.slideTo(0);
        }
      },

      download() {
        if (this.$parent.isWx) {
          this.isShowOpenOnBrowser = true
        }
      },

      toggleMask() {
        this.isShowOpenOnBrowser = !this.isShowOpenOnBrowser
      },
      // 提交评论
      submitComment() {
        const recording_id = this.$route.query.recid
        const user_id = this.$route.query.uid
        const content = this.commentTxt
        const commentator_id = this.viewerid
        const commentator_nickname = _get(this.userInfo, 'nickname')
        const commentator_avatar = _get(this.userInfo, 'headimgurl')
        if (commentator_id && content) {
          const loading = this.$message({
            type: 'loading'
          })
          this.$api.comment.summitComment({
            recording_id,
            user_id,
            comment: {
              content,
              commentator_id,
              commentator_nickname,
              commentator_avatar,
              time: new Date(),
            }
          }).then(() => {
            loading.close()
            this.commentTxt = ''
            const size = (Math.ceil(this.comments.length / PAGE_SIZE) * PAGE_SIZE) - 1
            this.getCommentListData(0, size, true).then(() => {
              this.$nextTick(() => {
                this.bscroll.refresh()
              })
            })
          }).catch(() => {
            loading.close()
          })
        } else if (!commentator_id) {
          this.$message({
            message: '请先登录或使用微信打开本网页!',
            duration: 1500,
          })
        } else if (!content) {
          this.$message({
            message: '评论不能为空!',
            duration: 1500,
          })
        }
      },
      // 点赞
      submitPraise() {
        if (this.isViewerLike) {
          // 点赞过了不能再点赞 或者 取消
          return
        }

        const recording_id = this.$route.query.recid
        const viewer_id = this.viewerid
        if (viewer_id) {
          const loading = this.$message({
            type: 'loading'
          })
          this.$api.comment.submitPraise({
            recording_id,
            viewer_id
          }).then(() => {
            loading.close()
            this.getCommentListData();
          }).catch(() => {
            loading.close()
          })
        } else if (!viewer_id) {
          this.$message({
            message: '请先登录!',
            duration: 1500,
          })
        }
      },
      // 删除评论
      deleteComment() {
        this.getCommentListData(0, this.comments.length, true).then(() => {
          this.$nextTick(() => {
            this.bscroll.refresh()
          })
        })
      },
      // 分享
      share() {
        this.$shareMask_()
      },
      // 滚动条
      initScroll() {
        this.bscroll = new BScroll('.home', {
          click: true,
          scrollY: true,
          mouseWheel: {
            speed: 20,
            invert: false,
            easeTime: 300
          },
          bounce: {
            top: false,
            bottom: false,
            left: false,
            right: false
          }
        })

        this.bscroll.on('scrollEnd', () => {
          // 滚动到底部
          if (this.bscroll.y <= (this.bscroll.maxScrollY + 50)) {
            console.log('到底了！')
            if (!this.isCommentLoading && this.isCommentsMore) {
              this.getCommentListData(this.comments.length, (this.comments.length + PAGE_SIZE - 1)).then(() => {
                this.bscroll.refresh()
              })
            }
          }
        })
      },

      init() {
        Promise.all([this.getAudioShareData(), this.getUserInfo()]).then(() => {
          if (this.userInfo) {
            this.getCommentListData().then(() => {
              this.$nextTick(() => {
                this.initScroll()
              })
            }).catch(() => {
              this.$nextTick(() => {
                this.initScroll()
              })
            });
          } else {
            this.$nextTick(() => {
              this.initScroll()
            })
          }
        }).catch(() => {
          this.$nextTick(() => {
            this.initScroll()
          })
        })}
    },
    created() {
      this.getOrgName()
      this.bscroll = null
    }
  }
</script>

<style lang="scss" src="../scss/home.scss" scoped/>
<style lang="scss" src="../scss/home-green.scss" scoped/>
<style lang="scss" src="../scss/home-blue.scss" scoped/>

<style scoped>
  .long_sentence {
    font-size: 14px;
    display: inline-block;
    text-align: left;
    color: #666666;
    font-family: Arial, Helvetica, sans-serif;
  }
</style>
